package com.example.fruit.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.fruit.MyApplication;
import com.example.fruit.R;
import com.example.fruit.adapter.FruitAdapter;
import com.example.fruit.bean.Fruit;
import com.example.fruit.util.KeyBoardUtil;
import com.example.fruit.util.SPUtils;
import com.example.fruit.widget.ActionBar;

import org.litepal.crud.DataSupport;

import java.util.List;
/**
 * 搜索水果
 */
public class SearchActivity extends AppCompatActivity {
    private ActionBar mTitleBar;//标题栏
    private Activity myActivity;
    private RecyclerView rvfruitList;
    private FruitAdapter mfruitAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private EditText etQuery;//搜索内容
    private ImageView ivSearch;//搜索图标
    private List<Fruit> mfruit;
    private String account;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        myActivity = this;
        rvfruitList = findViewById(R.id.rv_fruit_list);
        llEmpty = findViewById(R.id.ll_empty);
        etQuery=findViewById(R.id.et_query);
        ivSearch=findViewById(R.id.iv_search);
        mTitleBar = (ActionBar)findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity,"搜索水果", R.drawable.ic_back, 0, 0,getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        //获取控件
        initView();
        //搜索
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog dialog = new ProgressDialog(myActivity);
                dialog.setMessage("正在搜索···");
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadData();//加载数据
                        dialog.dismiss();
                    }
                }, 1300);
            }
        });
        //点击软键盘中的搜索
        etQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                ProgressDialog dialog = new ProgressDialog(myActivity);
                dialog.setMessage("正在搜索···");
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            KeyBoardUtil.hideKeyboard(v);//隐藏软键盘
                            loadData();//加载数据
                           // return true;
                        }
                        dialog.dismiss();
                    }
                }, 1300);
                return false;
            }
        });

    }

    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager=new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvfruitList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        mfruitAdapter=new FruitAdapter(llEmpty,rvfruitList);
        //=2.3、设置recyclerView的适配器
        rvfruitList.setAdapter(mfruitAdapter);
        loadData();
        mfruitAdapter.setItemListener(new FruitAdapter.ItemListener() {
            @Override
            public void ItemClick(Fruit fruit) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity,SPUtils.IS_ADMIN,false);
                String account = (String) SPUtils.get(myActivity,SPUtils.ACCOUNT,"");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                }else {//已经登录
                    Intent intent;
                    if (isAdmin){
                        intent = new Intent(myActivity, AddActivity.class);
                    }else {
                        intent = new Intent(myActivity, FruitDetailActivity.class);
                    }
                    intent.putExtra("fruit",fruit);
                    startActivityForResult(intent,100);
                }
            }
        });
    }
    private void loadData(){
        String content=etQuery.getText().toString();//获取搜索内容
        if ("".equals(content) ){
            mfruit = DataSupport.where().find(Fruit.class);
        }else {
            mfruit =DataSupport.where("title like ?","%"+content+"%").find(Fruit.class);//通过标题模糊查询
        }
        if (mfruit !=null && mfruit.size()>0){
            rvfruitList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            mfruitAdapter.addItem(mfruit);
        }else {
            rvfruitList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK){
            loadData();//加载数据
        }
    }
}
